from django.contrib import messages
from django.http import HttpRequest, HttpResponse, HttpResponseNotFound
from django.shortcuts import render, redirect
from django.views.decorators.http import require_http_methods
from server.apps.todo.models import Task
from server.apps.todo.forms import TaskForm

@require_http_methods(['GET'])
def index(request: HttpRequest) -> HttpResponse:
    tasks = Task.objects.filter(is_deleted=False).filter(is_completed=False).order_by('-id')
    return render(request, 'todo/index.html', {'title': 'Главная', 'tasks': tasks})

@require_http_methods(['GET', 'POST'])
def create(request: HttpRequest) -> HttpResponse:
    error = ''
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('main')
        else:
            error = 'Форма была неверной'

    form = TaskForm()
    context = {
        'form': form,
        'error': error
    }
    return render(request, 'todo/create.html', context, {'title': 'Создание нового дела'})

@require_http_methods(['GET'])
def show_all(request: HttpRequest) -> HttpResponse:
    tasks = Task.objects.filter(is_deleted=False).order_by('id')
    return render(request, 'todo/show_all.html', {'title': 'Просмотр всех дел', 'tasks': tasks})


@require_http_methods(['GET'])
def show_one(request: HttpRequest, id: int) -> HttpResponse:
    task = Task.objects.get(id=id)
    print(task)
    return render(request, 'todo/show_one.html', {'title': 'Просмотр одного дел', 'tasks': task})


@require_http_methods(['GET', 'POST'])
def edit(request: HttpRequest, id: int) -> HttpResponse:
    task = Task.objects.get(id=id)
    if request.method == "POST":
        task.title = request.POST.get("title")
        task.task = request.POST.get("task")
        task.is_completed = bool(request.POST.get("is_completed"))
        task.save()
        return redirect("main")
    else:
        return render(request, 'todo/edit.html', {'title': 'Редактирование делаmmmm', 'tasks': task})


@require_http_methods(['GET'])
def delete(request: HttpRequest, id: int) -> HttpResponse:
    task = Task.objects.get(id=id)
    task.is_deleted = True
    task.save()
    return redirect("main")